<?php
/**
 * 用户相关函数 - JBlog
 * 
 * @copyright (c) 2008-2010 JBlog (www.lisijie.org)
 * @author lisijie <lisijie86@gmail.com>
 * @version $Id: func_user.php 289 2010-04-12 07:32:08Z lisijie86 $
*/

!defined('IN_JBLOG') && exit('Access Denied!');

//用户身份验证
function check_user() {
	global $_USER;
	if ( false === ($auth = get_cookie('auth')) ) return false;
	list($userid, $password) = explode("\t", authcode($auth, 'DECODE'));
	if ( is_numeric($userid) ) {
		$sesfile = DATA_ROOT.'session'.DS.md5(JBLOG_KEY.$userid).'.php';
		if ( file_exists($sesfile) && NOW - filemtime($sesfile) < 1800 ) {
			$userinfo = str_replace("<?php exit();?>\n", '', file_get_contents($sesfile));
			$userinfo = unserialize($userinfo);
		} else {
			$userinfo = get_user($userid, 'id');
			@file_put_contents($sesfile, "<?php exit();?>\n".serialize($userinfo));
		}
		if ( $userid == $userinfo['id'] && $password == md5($userinfo['password'].$userinfo['userkey'].$_SERVER['HTTP_USER_AGENT']) ) {
			$_USER['id'] = $userinfo['id'];
			$_USER['name'] = addslashes($userinfo['username']);
			$_USER = array_merge($_USER, $userinfo);
			return true;
		}
	}
	user_logout();
}

/**
 * 用户登陆
 * 
 * @param string $account 帐号
 * @param string $password 密码
 * @param int $remember 是否记住状态
 * @return int -1 用户不存在; -2 帐号或密码错误; -3 未通过审核; 1 登录成功
 */
function user_login($account, $password, $remember = 0) {
	$field = is_email($account) ? 'email' : 'username';
	if ( $field == 'username' && !is_username($account) ) return -1;
	$userinfo = get_user($account, $field);
	if ( !$userinfo ) return -1;
	if ( md5($password) != $userinfo['password'] ) {
		return -2;
	} else {
		if ( !$userinfo['ischeck'] ) return -3;
		$userkey = random(10);
		$cookie = authcode("{$userinfo[id]}\t".md5($userinfo['password'].$userkey.$_SERVER['HTTP_USER_AGENT']));
		$expire = $remember ? 86400*365 : 0;
		set_cookie('auth', $cookie, $expire);
		update_user($userinfo['id'], array('userkey'=>$userkey, 'lastlogin'=> NOW, 'logincount'=>$userinfo['logincount']+1, 'lastip'=>get_onlineip()));
		@unlink(DATA_ROOT.'session'.DS.md5(JBLOG_KEY.$userinfo['id']).'.php');
		return 1;
	}
}

//获取用户资料
function get_user($key, $field = 'username') {
	global $db;
	if ( !in_array($field, array('id', 'username', 'email')) ) {
		return false;
	} elseif ( $field == 'id' && !is_numeric($key) ) {
		return false;
	} elseif ( $field == 'username' && !is_username($key) ) {
		return false;
	} elseif ( $field == 'email' && !is_email($key) ) {
		return false;
	}
	$userinfo = $db->fetch_one_array("SELECT * FROM ".tname('user')." WHERE `{$field}` = '{$key}'");
	if ( !$userinfo ) return false;
	$userinfo = apply_filter('get_user', $userinfo);
	return $userinfo;
}

//更新用户资料
function update_user($userid, $updata) {
	global $db;
	$updata = apply_filter('update_user', $updata);
	$db->update('user', $updata, array('id'=>intval($userid)));
}

//注销登录
function user_logout() {
	set_cookie('auth', '');
}

//用户名保留关键字
function is_banname($username) {
	$banname = explode(',', config('banname'));
	if (count($banname)) {
		foreach ($banname as $val) {
			if (empty($val)) continue;
			if (strpos($username, $val) !== false) {
				return true;
			}
		}
	}
	return false;
}

//是否合法Email地址
function is_email($email) {
	if (preg_match('/^[0-9a-z]+[0-9a-z_\.\-]*@[0-9a-z\-]+(\.[a-z]{2,4}){1,2}$/i',$email)) {
		return true;
	}
	return false;
}

//E-mail是否已使用
function email_exist($email, $except_uid = 0) {
	global $db;
	return $db->result("SELECT id FROM ".tname('user')." WHERE email = '$email' AND id != '$except_uid'");
}

//是否合法用户名
function is_username($username) {
	if ( empty($username) ) return FALSE;
	$badchars = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','$','(',')','%','@','+','?',';','^');
	foreach ($badchars as $char) {
		if (strpos($username,$char) !== false) {
			return false;
		}
	}
	return true;
}

function authcode($string, $method = 'ENCODE') {
	$key = substr(md5($_SERVER['HTTP_USER_AGENT'].JBLOG_KEY),-10);
	$keylen = strlen($key);
	$strlen = strlen($string);
	$string = $method == 'DECODE' ? base64_decode($string) : $string;
	$code = '';
	for ( $i=0; $i<$strlen; $i++ ) {
		$k = $i % $keylen;
		$code .= $string{$i} ^ $key{$k};
	}
	return ($method == 'ENCODE' ? base64_encode($code) : $code);
}
?>